<template>
  <div class="container">
    <!-- 左侧树结构 -->
    <div class="tree-container">
      <a-input-search v-model:value="searchValue" placeholder="输入关键字搜索" style="margin-bottom: 8px" />
      <a-tree
        :expanded-keys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        :tree-data="filteredTreeData"
        :replaceFields="{ children: 'children', title: 'title', key: 'key' }"
        @select="handleSelect"
        @expand="onExpand"
      >
        <template #title="{ title }">
          <span v-if="title.indexOf(searchValue) > -1">
            {{ title.substr(0, title.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ title }}</span>
        </template>
      </a-tree>
    </div>
    <div class="table-container">
      <!--引用表格-->
      <BasicTable @register="registerTable" :rowSelection="rowSelection">
        <!--插槽:table标题-->
        <template #tableTitle>
          <a-button v-if="showAddButton" type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        </template>
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
        </template>
        <!--字段回显插槽-->
        <template v-slot:bodyCell="{ column, record, index, text }"> </template>
      </BasicTable>
      <!-- 表单区域 -->
      <SysAlarmRuleModal @register="registerModal" @success="handleSuccess"></SysAlarmRuleModal>
    </div>
  </div>
</template>

<script lang="ts" name="xichang-sysAlarmRule" setup>
  import { ref, reactive, computed, unref, onMounted, nextTick, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import SysAlarmRuleModal from './components/SysAlarmRuleModal.vue';
  import { columns, searchFormSchema, superQuerySchema } from './SysAlarmRule.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './SysAlarmRule.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  const queryParam = reactive<any>({});
  import type { TreeDataItem } from 'ant-design-vue/es/tree/Tree';

  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();

  import { convertToTreeData } from './treeUtils';
  import { getDeviceTree } from './dataApplication.api';
  const treeData = ref<TreeProps['treeData']>([]);
  const currentSelectedLevel = ref<number>(0);
  const fetchData = async () => {
    const res = await getDeviceTree();
    const filteredData = res.deviceOneList.map((one) => ({
      ...one,
      deviceTwoList: one.deviceTwoList?.map((two) => ({
        ...two,
        // 核心筛选
        deviceThreeList: two.deviceThreeList?.filter((three) => !(three.agreementName === 'udp' && three.fileAddr === null)),
      })),
    }));
    treeData.value = convertToTreeData(filteredData);
    generateList(treeData.value); // 生成扁平数据
  };
  // 新增展开事件
  const onExpand = (keys: string[]) => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
  };
  onMounted(() => {
    nextTick(fetchData);
  });
  // 新增搜索相关变量
  const searchValue = ref<string>('');
  const expandedKeys = ref<string[]>([]);
  const autoExpandParent = ref<boolean>(true);
  const dataList = ref<TreeDataItem[]>([]);
  // 生成扁平数据列表
  const generateList = (data: TreeDataItem[]) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      dataList.value.push({ key: node.key, title: node.title });
      if (node.children) {
        generateList(node.children);
      }
    }
  };

  // 获取父节点key
  const getParentKey = (key: string, tree: TreeDataItem[]): string | undefined => {
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          return node.key;
        }
        const parentKey = getParentKey(key, node.children);
        if (parentKey) return parentKey;
      }
    }
  };

  // 监听搜索值变化
  watch(searchValue, (value) => {
    const expanded = dataList.value
      .map((item) => {
        if (item.title!.indexOf(value) > -1) {
          return getParentKey(item.key as string, treeData.value || []);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    expandedKeys.value = expanded as string[];
    autoExpandParent.value = true;
  });
  // 修改后的过滤树数据
  const filteredTreeData = computed(() => {
    if (!searchValue.value) return treeData.value;

    const filterTree = (data: TreeDataItem[]): TreeDataItem[] => {
      return data
        .filter((item) => {
          const match = item.title!.includes(searchValue.value);
          if (item.children) {
            const childMatch = filterTree(item.children);
            if (childMatch.length) return true;
          }
          return match;
        })
        .map((item) => ({
          ...item,
          children: item.children ? filterTree(item.children) : [],
        }));
    };

    return filterTree(treeData.value || []);
  });

  const handleSelect = (selectedKeys, { node }) => {
    currentSelectedLevel.value = node.level; // 记录当前选中层级
    Object.keys(queryParam).forEach((key) => delete queryParam[key]);
    // 根据节点层级设置不同参数
    const params = {};
    switch (node.level) {
      case 1:
        params.deviceMark = node.rawData.deviceMark;
        break;
      case 2:
        // 新增父级设备标识参数
        // console.log(node.parent.node.rawData.deviceMark,'node')
        params.deviceMark = node.parent.node.rawData.deviceMark;
        params.deviceCla = node.rawData.deviceId;
        break;
      case 3:
        console.log(node, ' node.parent.node');
        params.deviceMark = node.parent.parent.node.rawData.deviceMark;
        params.deviceCla = node.parent.node.rawData.deviceId;
        params.deviceCategory = node.rawData.deviceName || node.rawData.id;
        break;
      case 4:
        params.deviceMark = node.parent.parent.parent.node.rawData.deviceMark;
        params.deviceCla = node.parent.parent.node.rawData.deviceId;
        params.deviceCategory = node.parent.node.rawData.deviceName || node.parent.node.rawData.id;
        params.needField = node.rawData.field;
        params.deviceId = node.parent.node.rawData.id; // 获取第三层节点ID
        params.agreementId = node.parent.node.rawData.agreementId; // 获取第三层节点ID
        break;
    }
    // 清空下级参数（使用实际参数名）
    const clearParams = [];
    switch (node.level) {
      case 1:
        clearParams.push('deviceCla', 'deviceCategory', 'needField');
        break;
      case 2:
        clearParams.push('deviceCategory', 'needField');
        break;
      case 3:
        clearParams.push('needField');
        break;
    }

    clearParams.forEach((param) => delete queryParam[param]);
    Object.assign(queryParam, params);
    reload();
  };
  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '告警规则表',
      api: list,
      columns,
      canResize: false,

      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '告警规则表',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const showAddButton = computed(() => {
    // 获取当前表格数据
    const tableData = getDataSource();
    return currentSelectedLevel.value === 4 && tableData?.length === 0;
  });

  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
      // 传递父级ID到表单
      initialValues: {
        deviceMark: queryParam.deviceMark, // 新增设备标识
        deviceCla: queryParam.deviceCla, // 新增设备分类
        deviceCategory: queryParam.deviceCategory, // 新增设备类别
        needField: queryParam.needField, // 新增需求字段
        deviceId: queryParam.deviceId, // 新增需求字段
        agreementId: queryParam.agreementId, // 新增需求字段
      },
    });
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
    ];
  }
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        // auth: 'xichang:sys_alarm_rule:delete',
      },
    ];
  }
</script>

<style lang="less" scoped>
  // 新增布局样式（放在原有样式之前）
  .container {
    display: flex;
    width: 100%;
    height: calc(100vh - 111px); /* 根据实际布局调整减去的像素值 */
    min-width: 100%;
    padding: 16px;
    background: #fff;
    box-sizing: border-box;
    .tree-container {
      width: 20%;
      height: 100%; /* 新增高度限制 */
      padding: 16px;
      padding-top: 40px;
      overflow-y: auto; /* 添加垂直滚动 */
      box-shadow: 4px 0 6px -4px rgba(0, 0, 0, 0.1);
      :deep(.ant-tree) {
        padding: 16px !important; /* 减少内边距 */
        min-width: 300px; /* 保证最小宽度 */
        .ant-tree-treenode {
          margin: 4px 0 !important;
          white-space: nowrap; /* 防止节点换行 */
          .ant-tree-node-content-wrapper {
            padding: 4px 8px !important;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .ant-tree-switcher {
            line-height: 30px;
          }
        }
      }
    }

    .table-container {
      flex: 1;
      height: 100%; /* 新增高度限制 */
      min-width: calc(65% - 16px);
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
  }

  // 保留原有样式
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
